package model

import (
	"conf"
	"os"
)

type RedirectModel struct {
	Ctr string
	Act string
}

type LogOnModel struct {
	UserName string
	Password string
}

type Article struct {
	Title   string
	Content string
}

type ArticleListModel struct {
	Articles []*Article
}

var articleCache *ArticleListModel

func init() {
	articleCache = ListArticle()
}

func ListArticle() *ArticleListModel {
	if articleCache != nil {
		return articleCache
	}

	c, _ := conf.ReadConfigFile("testdata.dat")
	options, _ := c.GetOptions("article")
	result := new(ArticleListModel)
	result.Articles = make([]*Article, len(options))
	for i, option := range options {
		content, _ := c.GetString("article", option)
		result.Articles[i] = &Article{option, content}
	}
	return result
}

func (this *ArticleListModel) GetArticle(title string) *Article {

	for _, a := range articleCache.Articles {
		if a.Title == title {
			return a
		}
	}

	return nil
}

type Error string

func (this Error) String() string {
	return string(this)
}

func (this *Article) Save() os.Error {
	c, err := conf.ReadConfigFile("testdata.dat")
	if err != nil {
		return (Error)("Cannot open the database file : " + err.String())
	}
	c.AddOption("article", this.Title, this.Content)
	w, _ := os.Open("testdata.dat", os.O_WRONLY, 0)
	c.Write(w, "")
	w.Close()

	// refresh articles
	articleCache = nil
	articleCache = ListArticle()
	return nil
}
